<script setup lang="ts">
import { ref, toRaw } from 'vue';
import { ElMessage } from 'element-plus';
import { type Scene } from 'three';
import { ColorPicker } from "vue3-colorpicker";
import "vue3-colorpicker/style.css";
import Light from '@/utils/light';
import type { LightType } from "@/types/components/three.d.ts"
import type { BaseSelectOption } from "@/types/components/form.d.ts";

const props = defineProps<{
    scene: Scene;
}>();
const selectVal = ref<LightType | undefined>(undefined);
const pureColor = ref('#fff');
const options: BaseSelectOption[] = [
    { label: '环境光', value: 'ambient' },
    { label: '平行光', value: 'directional' },
    { label: '点光源', value: 'point' },
    { label: '聚光灯', value: 'spot' },
]
const lightList = ref<Light[]>([]);

const add = () => {
    console.log(selectVal.value, pureColor.value);
    if (!selectVal.value) return ElMessage.error('请选择灯光类型');
    if (props.scene) {
        const light = new Light(selectVal.value, { color: pureColor.value })
        lightList.value.push(light);
        props.scene.add(light.getObject3D())
        ElMessage.success('光源添加成功');
    }
}

const removeLight = (index: number) => {
    if (!props.scene || !lightList.value[index]) return ElMessage.error('场景或光源不存在');
    const lightObj = lightList.value[index].getObject3D();
    // 从场景中移除光源对象
    props.scene.remove(toRaw(lightObj));
    // 从 lightList 中移除光源实例
    lightList.value.splice(index, 1);
    ElMessage.success('光源已移除');
};

const getLabelByValue = (value) => {
    const label = options.find(item => item.value === value)?.label;
    return label
}
</script>

<template>
    <div class="absolute right-0">
        <div class="flex flex-col">
            <div class="flex flex-row items-center pb-2">
                <el-select class="mr-1" v-model="selectVal" placeholder="Select" style="width: 240px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <color-picker v-model:pureColor="pureColor" shape="circle" />
                <el-button class="ml-1" type="primary" @click="add">增加</el-button>
            </div>
            <div class="flex flex-col pl-2 pr-2">
                <div v-for="(item, idx) in lightList" class="flex items-center justify-between text-[#fff]">
                    <span>{{ getLabelByValue(item.type) }}</span>
                    <el-icon color="#F56C6C" class="cursor-pointer" @click="removeLight(idx)">
                        <Delete />
                    </el-icon>
                </div>
            </div>
        </div>
    </div>

</template>

<style scoped></style>